/**
 * 
 */
package neptune.manager.validator.rules.ipaddress;

import neptune.manager.builder.IPAddressRange;
import neptune.manager.model.topology.IPAddress;
import neptune.manager.utils.IllegalValueException;
import neptune.manager.utils.Logger.MessageType;
import neptune.manager.validator.ValidatorResult;
import neptune.manager.validator.ValidatorRule;
import neptune.manager.validator.Validator.Status;

/**
 * @author Roberto Bifulco [RobertoBifulco.it] [info@robertoBifulco.it]
 * 
 */
public class ControlIpAddressFormatRule extends ValidatorRule<IPAddress> {

	private IPAddressRange controlIpRange;

	public ControlIpAddressFormatRule(IPAddressRange controlIpRange) {
		super();
		this.controlIpRange = controlIpRange;
	}

	@Override
	public String getName() {
		return "ControlIpAddressFormat";
	}

	@Override
	protected ValidatorResult validationAlgorithm(IPAddress toValidate,
			ValidatorResult result) {

		if (!toValidate.isControlAddress())
			return result;
		
		try {
			if (!controlIpRange.isInRange(toValidate)) {
				result.setStatus(Status.ERROR);
				result
						.getLog()
						.addMessage(
								"IP address '"
										+ toValidate.getAddress()
										+ "' is not in the control Ip address range",
								MessageType.ERROR);
			}
		} catch (IllegalValueException e) {
			result.setStatus(Status.ERROR);
			result.getLog().addMessage(
					"Unable to verify IP address '" + toValidate.getAddress(),
					MessageType.ERROR);
		}

		return result;
	}
}
